<?php

use Illuminate\Database\Capsule\Manager as DB;

#前台基类
abstract class CommonController extends CoreController
{
    protected $user;

    protected $authExcept = [];

    public function init()
    {
        parent::init();
        $authExcept = array_map('strtolower', $this->authExcept);
        if (in_array($this->action, $authExcept)) {
            // Log::out("{$this->controller}:{$this->action}" . ' no need login');
            $this->user = \app\service\auth::checklogin();
        } else {
            // Log::out("{$this->controller}:{$this->action}" . ' need login');
            $this->user = \app\service\auth::checklogin(true);
        }
        //$this->checkSign();
    }

    private function RSA_openssl($data,$type='encode')
    {
        if (empty($data)) {
            return 'data参数不能为空';
        }
        if (is_array($data)) {
            return 'data参数不能是数组形式';
        }

        $rsa_public = '';
        if(empty($rsa_public)){
            $rsa_public = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDuif6p94zwnG4DzTz6UJa3JeW1
7JoFTDxOeNhnVA85ePV5f/BAn4DMkQ1HwCRvo1/gxoUgZqZQVzyMjyK/QCsQ1Vcs
UNny3bwrWHPFDs3kPPln8ZPalE14PWN8bf3b5CkITpJXP2RBqgtRQnTMxNQCW87p
BH7y2gR0dWtpEzV9owIDAQAB
-----END PUBLIC KEY-----';
        }
        $rsa_private = '';
        if(empty($rsa_private)){
            $rsa_private = '-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDuif6p94zwnG4DzTz6UJa3JeW17JoFTDxOeNhnVA85ePV5f/BA
n4DMkQ1HwCRvo1/gxoUgZqZQVzyMjyK/QCsQ1VcsUNny3bwrWHPFDs3kPPln8ZPa
lE14PWN8bf3b5CkITpJXP2RBqgtRQnTMxNQCW87pBH7y2gR0dWtpEzV9owIDAQAB
AoGBAJI8FNw7/7JOI/++paBLIWpcGEwEJZQT3XC6EuidlsvEBLEcprvnTL2cOwj+
mRe7j36sFVb8tv7PzDXbVhDrFLqJG40CD9D5enb+DiLZQaJRgbZ/C+So90Q7NPda
OxKHQyrWH/8bV5tHAqDst1RGzHD2uf5J1joo+O/ytJG28XUBAkEA+l0fFquEgTFB
ej6FfLghGRT2yPRCIXMvS+Y/2OnrLb8T+te1I6MnKwJx37M3FiZ1uHVy/fqBZPex
ebnVRF26gQJBAPPoudrL7DpuesQR7hXjmytCCZYm+qbcHMVc+qBkOf+5My07TdHt
EKQ4mq0oe6cXRZkHBCMMCQQFEKUffqTZ/iMCQAYuWmAi5+iQoL813/HOUfLek6Eu
dpuAzoAfNSBT1hyRBRtCTBSPKJ5lNw6AzDFdzbY6IBapIpytiNIqhltjvQECQAoB
9YY9sb6gA9eBqNQrF5XJytznUoeAJooOi5YDJsIQVkI32bSQVot2axpJu/EaKlfi
CtBpUQFiN9GenjKjYyMCQFfZRN+4oYkgwwL4tYkyA8BODpAX+Fx+/aDD6L/sCNHX
mcAgUIGH1epo+7Qwr+QGczj3W2nYoPgbmW/9zW0hFg4=
-----END RSA PRIVATE KEY-----';
        }

        //私钥解密
        if ($type=='decode') {
            $private_key = openssl_pkey_get_private($rsa_private);
            if (!$private_key) {
                return('私钥不可用');
            }
            $return_de = openssl_private_decrypt(base64_decode($data), $decrypted, $private_key);
            if (!$return_de) {
                return('解密失败,请检查RSA秘钥');
            }
            return $decrypted;
        }

        //公钥加密
        $key = openssl_pkey_get_public($rsa_public);
        if (!$key) {
            return('公钥不可用');
        }
        //openssl_public_encrypt 第一个参数只能是string
        //openssl_public_encrypt 第二个参数是处理后的数据
        //openssl_public_encrypt 第三个参数是openssl_pkey_get_public返回的资源类型
        $return_en = openssl_public_encrypt($data, $crypted, $key);
        if (!$return_en) {
            return('加密失败,请检查RSA秘钥');
        }
        return base64_encode($crypted);
    }

    #中间件验证登陆标识
    private function checkToken()
    {
        $middle      = "app\\middleware\\" . strtolower($this->controller);
        if (class_exists($middle)) {
            $this->user = (new $middle)->handle($this->pageParam);
        }
    }

    #验证角色权限
    private function checkRole()
    {
        #检查权限
        $allAuth = remember('role_' . $this->user->user_id, 3600, function () {
            $ownAuth = explode(',', DB::table('members_roles')->find($this->user->roles_id)->menu_ids);
            $rows    = DB::table('members_menus')->whereIn('id', array_values($ownAuth))->select('module', 'controller', 'actions')->get();
            $auth    = [];
            if ($rows->isNotEmpty()) {
                foreach ($rows as $k => $v) {
                    $allact = explode(',', $v->actions);
                    foreach ($allact as $action) {
                        if (!empty($v->module) && !empty($v->controller) && !empty($action)) {
                            array_push($auth, strtolower('/' . $v->module . '/' . $v->controller . '/' . $action));
                        }
                    }
                }
            }
            return $auth;
        });
        if (!in_array(strtolower('/' . $this->module . '/' . $this->controller . '/' . $this->action), $allAuth)) {
            throw new Exception('无访问权限.', 403);
        }
    }

    protected function cleanTableColumn($table, &$rows)
    {
        $columns = [];
        foreach (DB::select("SHOW COLUMNS FROM `{$this->config->database->prefix}{$table}`") as $v) {
            $columns[] = $v->Field;
        }
        foreach ($rows as $k => $v) {
            if (!in_array($k, $columns)) {
                unset($rows[$k]);
            }
        }
    }

}
